package com.xjc.common;

import lombok.Data;
import org.flowable.bpmn.model.Process;
import org.flowable.bpmn.model.SequenceFlow;
import org.flowable.bpmn.model.UserTask;
import org.flowable.common.engine.impl.interceptor.Command;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.impl.persistence.entity.ExecutionEntity;
import org.flowable.engine.impl.persistence.entity.ExecutionEntityManager;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.engine.impl.util.ProcessDefinitionUtil;

import java.util.UUID;

/**
 * <p>
 * 加签（加单人任务节点）
 * </p>
 *
 * @author xiaojincai
 * @since 2025-07-15
 */
@Data
public class InjectUserTaskCmd implements Command<Void> {
    private final String processInstanceId;
    private final String currentExecutionId;
    private final String assignee;
    private final String taskName;

    public InjectUserTaskCmd(String processInstanceId, String currentExecutionId, String assignee, String taskName) {
        this.processInstanceId = processInstanceId;
        this.currentExecutionId = currentExecutionId;
        this.assignee = assignee;
        this.taskName = taskName;
    }

    @Override
    public Void execute(CommandContext commandContext) {
        // 1. 获取流程实例运行时数据
        ExecutionEntityManager executionManager = CommandContextUtil.getExecutionEntityManager(commandContext);
        ExecutionEntity execution = executionManager.findById(currentExecutionId);

        // 2. 创建动态用户任务
        UserTask newTask = new UserTask();
        newTask.setId("dynamicTask_" + UUID.randomUUID().toString().replace("-", ""));
        newTask.setName(taskName);
        newTask.setAssignee(assignee);

        // 3. 构建顺序流连接
        SequenceFlow flow = new SequenceFlow();
        flow.setSourceRef(execution.getActivityId());
        flow.setTargetRef(newTask.getId());

        SequenceFlow newFlow = new SequenceFlow();
        newFlow.setSourceRef(newTask.getId());
//        newFlow.setTargetRef(execution.get());

        // 4. 注入流程定义
        Process process = ProcessDefinitionUtil.getProcess(execution.getProcessDefinitionId());
        process.addFlowElement(newTask);
        process.addFlowElement(flow);

        // 5. 更新运行时执行实例

        // 正确设置活动ID的方式
        execution.setVariable("targetActivityId", newTask.getId());
        executionManager.update(execution);

        return null;
    }
}

